/**
 * Created by tanbingqin on 2019/11/20.
 */
import { messages, deepFullCopy } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import constants from 'share/constants'
import { Button, Form, Switch, Input, Checkbox, Radio, InputNumber, Row, Col, message, Spin, Alert, Tooltip, Icon, Select, Affix, Popover } from 'antd'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
import formService from 'containers/setting/form/form.service'
import menuRoute from 'routes/menuRoute'
import Chooser from 'components/chooser'
import errorMessage from 'share/errorMessage'
import Priority from 'components/template/priority'
import InputLanguage from 'components/template/input-language'
import Permission from 'components/template/permission'
import AllocationExpense from 'containers/setting/form/comp/expense'
import AllocationLoanType from 'containers/setting/form/comp/loanType'
import AllocationVendorType from 'containers/setting/form/comp/vendorType'
import chooserData from 'share/chooserData'
import formUtil from 'containers/setting/form/form-util'
import BaseService from 'share/base.service';
import NumberRange from "containers/financial-management/expense-view/component/number-range";
import PrioritySimple from "components/template/priority-simple/priority-simple";

class FormNewEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      defaultPriorityLoading: false, //获取权限默认值的loading
      disabled: false, //所有表单适用这个属性
      //form上有个edit字段标记是否可编辑，现在后台返回的也一直是true
      loanDisabled: false, //借款单适用这个属性
      form: {},  //表单信息
      setOfBooksId: '', //表单上的帐套，如果是新建，则为所属组织上的帐套，租户级这个为空
      permissionTop: 'SET_OF_BOOK', //SET_OF_BOOK帐套级权限 COMPANY 公司级权限
      priorityValue: {}, //所属组织，启用公司控件value
      priorityRangeValue: {}, //所属组织控件的rangeValue，包含整个对象信息
      hasProcessDefaultPriority: false, //是否处理过所属组织的默认值
      userScopeValue: {
        range: 'ALL',
        value: []
      }, //适用人员控件value
      isPurchaseApplication: false, //如果是费用申请单，是否是费用申请单下的采购申请单
    };
    this.formDetail = menuRoute.getRouteItem('form-detail','key'); //表单详情页
    this.formList = menuRoute.getRouteItem('form-list','key'); //表单列表页
  }

  componentWillMount() {
    const { formOID } = this.context;
    this.initPriority(this.props.currentMenuPermission);
    if (formOID) {
      this.initFormData();
    }
  };

  componentWillReceiveProps(nextProps) {
    this.initPriority(nextProps.currentMenuPermission);
  };

  componentDidMount() {
    const { formOID, form, formType } = this.context;
    if (formOID) {
      this.props.form.setFieldsValue({
        valid: form.valid,
        formCode: form.formCode,
        sequence: form.sequence
      });
      if (formType !== 2005 && formType !== 2006 && formType !== 2201 && formType !== 3004) {
        this.initExpenseType();
      }
      //处理表单属性
      this.initCustomFormPropertyMap();
    }
  };

  initFormData = () => {
    const { form } = this.context;
    form.formNameI18n = form.i18n && form.i18n.formName && formUtil.processLanguageToLowerCase(form.i18n.formName);
    form.remarkI18n = form.i18n && form.i18n.remark && formUtil.processLanguageToLowerCase(form.i18n.remark);
    this.setState({
      form,
      disabled: !form.edit,
      setOfBooksId: form.setOfBooksId
    });
    //处理所属组织，启用公司
    this.initPriorityValue();
    //处理适用人员
    this.initUserScope();
    //处理借款单disabled
    this.initLoanDisabled();
  };

  //表单新建的时候初始化所属组织
  initDefaultPriority = () => {
    const { permissionTop, hasProcessDefaultPriority, defaultPriorityLoading } = this.state;
    const { formOID } = this.context;
    if (hasProcessDefaultPriority || formOID || defaultPriorityLoading) {
      //只处理一次默认值，新建表单的时候处理，编辑表单不处理
      return;
    }

    this.setState({defaultPriorityLoading: true});
    BaseService.dealDefaultPriority(permissionTop, 'oid', this.props.tenant).then(res => {
      if (res.priorityRangeValue && res.priorityValue) {
        res.priorityValue.priorityRangeValue = [res.priorityRangeValue];
      }
      this.setState(res);
      this.initFormCode(res.setOfBooksId);
    }).catch(error => {
      this.setState({defaultPriorityLoading: false});
      message.error(messages('common.error')/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/);
    }).finally(() => {
      this.setState({hasProcessDefaultPriority: true});
    });
  };

  //新建的时候初始化表单编码
  initFormCode = (setOfBooksId) => {
    const { formType } = this.context;
    if (setOfBooksId) {
      formService.getSobDetail(setOfBooksId).then(res => {
        let formCode = formUtil.generateFormCode(formType, res.data.setOfBooksCode);
        this.props.form.setFieldsValue({
          formCode
        });
      }).finally(() => {
        this.setState({defaultPriorityLoading: false});
      });
    } else {
      let formCode = formUtil.generateFormCode(formType, '');
      this.props.form.setFieldsValue({
        formCode
      });
      this.setState({defaultPriorityLoading: false});
    }
  };

  initPriorityValue = () => {
    const { form } = this.context;
    let priorityValue = {
      levelCode: form.fromType === 3 ? "TENANT" : (form.fromType === 2 ? "SET_OF_BOOK" : "COMPANY"),
      levelOrgId: form.fromType === 3 ? form.tenantId : (form.fromType === 2 ? form.setOfBooksId : form.companyOID),
      levelOrgName: form.fromType === 3 ? form.tenantName : (form.fromType === 2 ? form.setOfBooksName : form.companyName)
    };
    if ((form.fromType === 2 || form.fromType === 3) && form.customFormCompanyRequest.visibleCompanyScope === '2') {
      priorityValue.enableCompany = 'PART';
      priorityValue.distribution = form.customFormCompanyRequest.companyList;
    }
    let priorityRangeValue = {};
    if (form.fromType === 2) {
      priorityRangeValue = {
        setOfBooksId: form.setOfBooksId,
        setOfBooksName: form.setOfBooksName
      }
    }
    if (form.fromType === 1) {
      priorityRangeValue = {
        id: form.companyId,
        companyOID: form.companyOID,
        name: form.companyName,
        setOfBooksId: form.setOfBooksId
      }
    }
    if (form.fromType === 1 || form.fromType === 2) {
      priorityValue.priorityRangeValue = [priorityRangeValue];
    }
    this.setState({priorityValue, priorityRangeValue});
  };

  initUserScope = () => {
    const { form } = this.context;
    let userScopeValue = {
      range: 'ALL',
      value: []
    };
    if (form.customFormUserScopeDTO.visibleScope === 1002) {
      userScopeValue = {
        range: 'PERSON_GROUP',
        value: form.customFormUserScopeDTO.userGroups || []
      }
    }
    if (form.customFormUserScopeDTO.visibleScope === 1003) {
      let departmentList = form.customFormUserScopeDTO.departments || [];
      departmentList.map(department => {
        department.name = department.path;
        department.departmentOid = department.departmentOID;
      });
      userScopeValue = {
        range: 'DEPARTMENT',
        value: departmentList
      }
    }
    this.setState({userScopeValue});
  };

  initExpenseType = () => {
    const { form } = this.context;
    let rangeExpense = {
      range: 'ALL',
      value: []
    };
    if (form.expenseTypesDTO.visibleScope === 1004) {
      rangeExpense.range = 'RELATED';
    }
    if (form.expenseTypesDTO.visibleScope === 1002) {
      rangeExpense = {
        range: 'PARTIAL',
        value: form.expenseTypesDTO.expenseTypes
      };
    }
    this.props.form.setFieldsValue({rangeExpense});
  };

  initLoanDisabled = () => {
    const { formType, form } = this.context;
    let loanTypeVisibleScope = form.loanTypesDTO.visibleScope;
    //1004信用借款单，1005受控借款单
    if (loanTypeVisibleScope === 1004 || loanTypeVisibleScope === 1005) {
      this.setState({loanDisabled: true});
    }
  };

  initCustomFormPropertyMap = () => {
    const { form } = this.context;
    let propertyMap = form.customFormPropertyMap;
    for (let key in propertyMap) {
      if (formUtil.getFieldKey(key, propertyMap[key])) {
        this.props.form.setFieldsValue(formUtil.getFieldKey(key, propertyMap[key]));
      }
      if (formUtil.getStateKey(key, propertyMap[key])) {
        this.setState(formUtil.getStateKey(key, propertyMap[key]));
      }
    }
  };

  //初始化页面权限
  initPriority = (currentMenuPermission) => {
    let policyDTO = currentMenuPermission.currentMenuPermission && currentMenuPermission.currentMenuPermission.authPolicyCompDTO;
    let authPolicyAll = currentMenuPermission.currentMenuPermission && currentMenuPermission.currentMenuPermission.authPolicyAll;

    if (!policyDTO) {
      //如果没有policyDTO，说明currentMenuPermission还未拿到，此次不做处理，等拿到后再进行初始化
      return;
    }

    //authPolicyAll为true表示有租户权限,tenantFormRecommend表示允许选到租户级
    if (authPolicyAll && this.props.tenant.tenantFormRecommend) {
      this.setState({permissionTop: 'TENANT'}, this.initDefaultPriority);
    } else {
      if (policyDTO && policyDTO.setOfBooksIds && policyDTO.setOfBooksIds.length) {
        this.setState({permissionTop: 'SET_OF_BOOK'}, this.initDefaultPriority);
      } else {
        this.setState({permissionTop: 'COMPANY'}, this.initDefaultPriority);
      }
    }
  };

  //value为true 说明要刷新列表，为event点击事件时不做刷新
  goBack = (value) => {
    const { close } = this.context;
    if (close) {
      close(value);
    } else {
      this.context.router.push(this.formList.url);
    }
  };

  onPriorityChanged = (value) => {
    this.setState({priorityValue: value || {}});
    if (value && (value.levelCode === 'COMPANY' || value.levelCode === 'SET_OF_BOOK') && value.priorityRangeValue && value.priorityRangeValue.length) {
      this.setState({priorityRangeValue: value.priorityRangeValue[0], setOfBooksId: value.priorityRangeValue[0].setOfBooksId});
    } else {
      this.setState({priorityRangeValue: {}, setOfBooksId: ''});
    }
    this.clearDependency();
  };

  //表单所属组织切换了账套或者切换了公司，清楚依赖账套，公司查询的配置数据
  clearDependency = () => {
    const { formType } = this.context;
    let { userScopeValue } = this.state;
    userScopeValue.value = [];
    //所属组织账套，公司都用账套id
    //所属组织账套用账套id，所属组织公司用公司oid
    this.setState({
      userScopeValue
    });
    if (formType !== 2005 && formType !== 2006) {
      let rangeExpense = {
        range: 'ALL',
        value: []
      };
      this.props.form.setFieldsValue({rangeExpense});
    }
  };

  validateData = (values) => {
    const { formType } = this.context;
    const { priorityValue, userScopeValue, form } = this.state;
    if (!priorityValue.levelOrgId) {
      message.error(messages('request-2.key130')/*请选择所属组织*/);
      return false;
    }
    if ((priorityValue.levelCode === 'SET_OF_BOOK' || priorityValue.levelCode === 'TENANT')
      && priorityValue.enableCompany === 'PART'
      && !(priorityValue.distribution && priorityValue.distribution.length)) {
      message.error(messages('request-2.key131')/*请选择启用公司*/);
      return false;
    }
    if (((formType !== 3001 && formType !== 3002 && formType !== 3003) || !form.referenceOID) && form.entityType !== 4001) {
      if (!userScopeValue.range || (userScopeValue.range === 'PERSON_GROUP' && !userScopeValue.value.length)
        || (userScopeValue.range === 'DEPARTMENT' && !userScopeValue.value.length)) {
        message.error(messages('request-2.key132')/*请选择适用人员*/);
        return false;
      }
    }
    if (formType !== 2005 && formType !== 2006 && formType !== 2201 && formType !== 3004 && form.entityType !== 4001
      && values.rangeExpense && values.rangeExpense.range === 'PARTIAL' && !values.rangeExpense.value.length) {
      message.error(messages('request-2.key133')/*请选择可见费用类型*/);
      return false;
    }
    return true;
  };

  processValue = (values) => {
    const { formType, formOID } = this.context;
    const { form, setOfBooksId, priorityValue, priorityRangeValue, userScopeValue } = this.state;
    let params = {
      formType,
      formOID,
      id: form.id || undefined,
      tenantId: form.tenantId || undefined,
      valid: values.valid,
      sequence: values.sequence,
      formCode: values.formCode,
      iconName: '',
      fromType: priorityValue.levelCode === 'TENANT' ? 3 : (priorityValue.levelCode === 'SET_OF_BOOK' ? 2 : 1),
      formName: form.formName,
      remark: form.remark,
      i18n: {
        formName: formUtil.processLanguageToUpperCase(form.formNameI18n || []),
        remark: formUtil.processLanguageToUpperCase(form.remarkI18n || [])
      },
      setOfBooksId,
      companyId: priorityValue.levelCode === 'COMPANY' ? priorityRangeValue.id : null,
      associateExpenseReport: !formOID ? !!values.associateExpenseReport : undefined,
      customFormFields: form.customFormFields
    };
    //处理启用公司
    if (priorityValue.levelCode === 'SET_OF_BOOK' || priorityValue.levelCode === 'TENANT') {
      params.customFormCompanyRequest = {};
      if (formOID) {
        params.customFormCompanyRequest.customFormOID = formOID;
      }
      if (priorityValue.enableCompany === 'PART') {
        params.customFormCompanyRequest.visibleCompanyScope = 2;
        let companyOIDList = [];
        priorityValue.distribution.map(company => {
          companyOIDList.push(company.companyOID);
        });
        params.customFormCompanyRequest.companyOIDList = companyOIDList;
      } else {
        params.customFormCompanyRequest.visibleCompanyScope = 1;
        params.customFormCompanyRequest.companyOIDList = [];
      }
    }
    //处理适用人员
    if (((formType !== 3001 && formType !== 3002 && formType !== 3003) || !form.referenceOID) && form.entityType !== 4001) {
      params.customFormUserScopeDTO = {
        visibleScope: 1001,
        userGroupOIDs: [],
        departmentOIDs: []
      };
      if (formOID) {
        params.customFormUserScopeDTO.formOID = formOID;
      }
      if (userScopeValue.range === 'PERSON_GROUP') {
        let userGroupOIDs = [];
        userScopeValue.value.map(userGroup => {
          userGroupOIDs.push(userGroup.userGroupOID);
        });
        params.customFormUserScopeDTO = {
          visibleScope: 1002,
          userGroupOIDs: userGroupOIDs,
          departmentOIDs: []
        }
      }
      if (userScopeValue.range === 'DEPARTMENT') {
        let departmentOIDs = [];
        userScopeValue.value.map(department => {
          departmentOIDs.push(department.departmentOid);
        });
        params.customFormUserScopeDTO = {
          visibleScope: 1003,
          userGroupOIDs: [],
          departmentOIDs: departmentOIDs
        }
      }
    }
    //处理可见费用类型
    if (formType !== 2005 && formType !== 2006 && formType !== 2201 && formType !== 3004 && form.entityType !== 4001) {
      params.expenseTypesDTO = {
        visibleScope: 1001,
        expenseTypeOIDs: []
      };
      if (formOID) {
        params.expenseTypesDTO.entityOID = formOID;
      }
      if (values.rangeExpense.range === 'RELATED') {
        params.expenseTypesDTO.visibleScope = 1004;
      }
      if (values.rangeExpense.range === 'PARTIAL') {
        let expenseTypeOIDs = [];
        values.rangeExpense.value.map(expense => {
          expenseTypeOIDs.push(expense.expenseTypeOID);
        });
        params.expenseTypesDTO = {
          visibleScope: 1002,
          expenseTypeOIDs: expenseTypeOIDs
        }
      }
    }
    //处理表单属性
    params.customFormPropertyMap = this.processPropertyMap(values);
    return params;
  };

  //处理表单属性
  processPropertyMap = (values) => {
    const { formType, formOID } = this.context;
    const { isPurchaseApplication } = this.state;
    let propertyMap = {};
    //费用申请单表单属性
    //是否是采购申请单这个属性只有新建有
    if (formType === 2002 && !formOID) {
      propertyMap['public.shop.application'] = isPurchaseApplication;
    }
    return propertyMap;
  };

  handleSave = () => {
    const { formOID } = this.context;
    const { handleNew, refreshBase } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err && this.validateData(values)) {
        let params = this.processValue(values);
        this.setState({loading: true});
        let serviceName = params.formOID ? 'saveNewForm' : 'createNewForm';
        formService[serviceName](params).then(res => {
          this.setState({loading: false});
          message.success(messages('common.save.success',{arg1: res.data.formName})/*{arg1} 保存成功*/);
          if (formOID) {
            refreshBase(formOID, 'base');
          } else {
            handleNew(res.data);
          }
        }).catch((err) => {
          this.setState({loading: false});
          errorMessage(err.response);
        });
      }
    });
  };

  handleLanguageInput = (value, attr) => {
    let { form } = this.state;
    form[attr] = value.name;
    form[attr + 'I18n'] = value.i18n;
    this.setState({form});
  };

  handleStatusChange = (value, key) => {
    this.setState({
      [key]: value
    });
  };

  toGoReferenceDetail = (referenceOID) => {
    let url = this.formDetail.url.replace(':formOID', referenceOID);
    if (window.ISIE9) {
      url = `#${url}`;
    }
    window.open(url);
  };

  render() {
    const { profile, menuWidth } = this.props;
    const { formType, formOID } = this.context;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { loading, disabled, loanDisabled, form, setOfBooksId, permissionTop, priorityValue, userScopeValue,
      priorityRangeValue, hasProcessDefaultPriority, isPurchaseApplication, defaultPriorityLoading } = this.state;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 8, offset: 1},
    };
    return (
      <div className="form-new-edit new-form form-detail-base">
        <Spin spinning={loading}>
        <Form>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('valid', {
              valuePropName: 'checked',
              initialValue: true
            })(
              <Switch disabled={disabled || loanDisabled} />
            )}
          </FormItem>
          {(hasProcessDefaultPriority || formOID) && (
            <PrioritySimple
              top={permissionTop === 'TENANT' ? ['TENANT', 'SET_OF_BOOK', 'COMPANY'] : (permissionTop === 'SET_OF_BOOK' ? ['SET_OF_BOOK', 'COMPANY'] : ['COMPANY'])}
              priorityData={priorityValue}
              onChange={this.onPriorityChanged}
              formItemLayout={formItemLayout}
              disabledTop={!!formOID}
              disabled={disabled || loanDisabled || (formOID && priorityValue.levelCode === 'COMPANY')}
              tenantEnableCompany
              setEnableCompany
            />
          )}
          <FormItem {...formItemLayout} label={(
            <span> {messages('request-2.key28')/*顺序号*/}&nbsp;
              <Popover placement="top" content={messages('request-2.key29')/*序号之间尽量保持一定的步长，便于后续调整*/}>
                <Icon type="info-circle-o" style={{color: '#6C788C'}} />
              </Popover>
            </span>
          )}>
            <div className="normal-width">
              {getFieldDecorator('sequence', {
                rules: [
                  {
                    required: true,
                    message: messages('common.please.input')/*请输入*/  //请输入
                  }
                ],
                initialValue: formUtil.generateFormSequence(formType)
              })(
                <InputNumber style={{width: '100%'}} min={0} max={9999} precision={0} disabled={disabled || loanDisabled} />
              )}
            </div>
            <div style={{color: '#989898'}}>{messages('request-2.key30')/*表单排序按顺序号由小到大排序*/}</div>
          </FormItem>
          {(formType === 3001 || formType === 3002 || formType === 3003) && form.referenceOID && (
            <FormItem {...formItemLayout} label={messages('request-2.key134')/*适用人员*/}>
              <span>
                {messages('request-2.key135')/*如需编辑适用人员，请前往相关联的申请单设置*/}
              </span>
            </FormItem>
          )}
          {((formType !== 3001 && formType !== 3002 && formType !== 3003) || !form.referenceOID) && form.entityType !== 4001 && (
            <Permission
              onChange={value => this.handleStatusChange(value, 'userScopeValue')}
              formItemLayout={formItemLayout}
              hidden={(priorityValue.levelCode === 'SET_OF_BOOK' || priorityValue.levelCode === 'TENANT') ? ['DEPARTMENT'] : []}
              parser={value => ({range: value.range, value: value.value || []})}
              value={userScopeValue}
              componentProps={{
                'PERSON_GROUP': {
                  valueKey: 'userGroupOID',
                  listExtraParams:{
                    levelCode: priorityValue.levelCode,
                    levelOrgId: priorityValue.levelCode === 'TENANT' ? undefined : (priorityValue.levelCode === 'SET_OF_BOOK' ? priorityValue.levelOrgId : (priorityRangeValue && priorityRangeValue.id))
                  }
                },
                'DEPARTMENT': {
                  valueKey: 'departmentOid'
                }
              }}
              disabled={disabled || loanDisabled || !priorityValue.levelOrgId}
            />
          )}
          {!(formType === 2005 || formType === 2006 || formType === 2201) && formType !== 3004 && form.entityType !== 4001 && (
            <FormItem {...formItemLayout} label={messages('request-2.key136')/*可见费用类型*/}>
              <div className="normal-width">
                {getFieldDecorator('rangeExpense', {
                  initialValue: {
                    range: 'ALL',
                    value: []
                  }
                })(
                  <AllocationExpense
                    setOfBooksId={setOfBooksId || undefined}
                    disabled={disabled || loanDisabled || (priorityValue.levelCode !== 'TENANT' && !setOfBooksId)}
                    parser={value => ({range: value.range, value: value.value || []})}
                    hidden={(formType === 3001 || formType === 3002 || formType === 3003) && form.referenceOID ? [] : ['RELATED']}
                  />
                )}
              </div>
            </FormItem>
          )}
          <div className="sub-title">{messages('common.baseInfo')/*基本信息*/}</div>
          <FormItem {...formItemLayout} label={messages('request-2.key22')/*类型*/}>
            <span>{constants.getTextByValue(formType, 'documentTypeForShow')}</span>
          </FormItem>
          {form.referenceOID && (
            <FormItem {...formItemLayout} label={messages('request-2.key23')/*关联单据*/}>
              <span>
                <a onClick={() => this.toGoReferenceDetail(form.referenceOID)}>{form.referenceFormName}</a>
              </span>
            </FormItem>
          )}
          <FormItem {...formItemLayout} label={messages('request-2.key24')/*表单编码*/}>
            {getFieldDecorator('formCode', {
              rules: [
                {
                  max: 50,
                  message: messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/
                },
                {
                  required: true,
                  message: messages('common.please.input')/*请输入*/  //请输入
                },
                {
                  validator: (item, value, callback) => {
                    if(value && !value.match("^[0-9a-zA-Z_\-]*$")){
                      callback(messages('request-2.key25')/*只允许填写字母、数字、_或-*/);
                    }
                    callback();
                  }
                }
              ],
              initialValue: ''
            })(
              <Input
                type="text"
                autoComplete="off"
                placeholder={messages('common.please.input')/*请输入*/}
                disabled={disabled || loanDisabled || defaultPriorityLoading}
              />
            )}
            <div>{messages('request-2.key423')/*如果启用了编码规则定义，请尝试避免表单编码、公司编码、人员工号、编码规则定义内的固定字符之间相同的情况*/}</div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-2.key26')/*表单名称*/}>
            {getFieldDecorator('formName', {
              rules: [
                {
                  required: true,
                  validator: (item, value, callback) => {
                    if(!value || !value.name){
                      callback(messages('common.please.input')/*请输入*/);
                    }
                    callback();
                  }
                }
              ],
              initialValue: {
                name: form.formName,
                i18n: form.formNameI18n
              }
            })(
              <InputLanguage
                onChange={value => this.handleLanguageInput(value, 'formName')}
                placeholder={messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/}
                disabled={disabled || loanDisabled}
                maxLength={50}
              />
            )}
            <div style={{color: '#989898'}}>{messages('request-2.key27')/*名称可重复，请避免员工看到重名表单*/}</div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
            {getFieldDecorator('remark', {
              initialValue: {
                name: form.remark,
                i18n: form.remarkI18n
              }
            })(
              <InputLanguage
                onChange={value => this.handleLanguageInput(value, 'remark')}
                placeholder={messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/}
                disabled={disabled || loanDisabled}
                maxLength={50}
                textArea
                extraProps={{
                  rows: 3
                }}
              />
            )}
          </FormItem>
          {formType === 2002 && !formOID && (
            <FormItem {...formItemLayout} label={messages('request-2.key392')/*对公采购申请*/}>
              <RadioGroup
                disabled={disabled || loanDisabled}
                value={isPurchaseApplication}
                onChange={e => this.handleStatusChange(e.target.value, 'isPurchaseApplication')}
              >
                <Radio value={true}>{messages('common.yes')/*是*/}</Radio>
                <Radio style={{marginLeft: 50}} value={false}>{messages('common.no')/*否*/}</Radio>
              </RadioGroup>
            </FormItem>
          )}
          {(formType === 2001 || (formType === 2002 && !isPurchaseApplication)) && !formOID && (
            <FormItem {...formItemLayout} label={messages('request-2.key31')/*关联报销单*/}>
              {getFieldDecorator('associateExpenseReport', {
                initialValue: false
              })(
                <RadioGroup disabled={disabled || loanDisabled}>
                  <Radio value={true}>{messages('request-2.key32')/*关联*/}</Radio>
                  <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key46')/*不关联*/}</Radio>
                </RadioGroup>
              )}
              <div style={{color: '#989898'}}>{messages('request-2.key137')/*选择是，创建申请单时将自动生成对应的报销单*/}</div>
            </FormItem>
          )}
        </Form>
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar" style={{width: `calc(100vw - ${menuWidth}px)`}}>
          {!disabled && (
            <Button type="primary" loading={loading} onClick={this.handleSave}>{messages('common.ok')/*确定*/}</Button>
          )}
          <Button style={{marginLeft: 15}} onClick={e => this.goBack(true)}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

FormNewEdit.propTypes = {
  handleNew: React.PropTypes.func,
  refreshBase: React.PropTypes.func
};

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
    profile: state.login.profile,
    tenant: state.login.tenant,
    menuWidth: state.main.menuWidth,
  }
}

FormNewEdit.contextTypes = {
  formType: React.PropTypes.any,
  formOID: React.PropTypes.string,
  form: React.PropTypes.object,
  router: React.PropTypes.object,
  close: React.PropTypes.any
};

const WrappedFormNewEdit = Form.create()(FormNewEdit);

export default connect(mapStateToProps)(WrappedFormNewEdit)

